package com.example.park2212.news

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.park2212.R
import com.example.park2212.databinding.ActivityNewsBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = "/app/news/NewsActivity")
class NewsActivity : BaseActivity<ActivityNewsBinding,NewsViewModel>() {
    lateinit var newsAdapter: NewsAdapter
    override fun initView() {
        newsAdapter = NewsAdapter()
        binding.rvNews.adapter = newsAdapter
        binding.rvNews.layoutManager = LinearLayoutManager(this)

        binding.newsHead.headerTitle.setText("园区新闻")
        binding.newsHead.headerAdd.setOnClickListener {
            ARouter.getInstance().build("/app/news/NewsAddActivity").navigation()
        }


        binding.newsSv.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                if (query != null){
                    viewModel.newsSearch(query)
                }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return true
            }

        })

        newsAdapter.setOnItemClickListener { adapter, view, position ->
            viewModel.newsDelete(newsAdapter.data[position].id)
            newsAdapter.data.removeAt(position)
            newsAdapter.notifyItemRemoved(position)
        }
    }

    override fun initData() {
        viewModel.getNewsSuccess.observe(this){
            newsAdapter.data.clear()
            newsAdapter.data.addAll(it)
            newsAdapter.notifyDataSetChanged()
        }

        viewModel.newsSearchSuccess.observe(this){
            newsAdapter.data.clear()
            newsAdapter.data.addAll(it)
            newsAdapter.notifyDataSetChanged()
        }

        viewModel.newsDeleteSuccess.observe(this){
            ToastUtils.showLong("删除成功")
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.getNews()
    }

}